package com.ztesoft.zcm.cmdb.util;

import com.ztesoft.zcm.cmdb.domain.extra.UserDto;
import com.ztesoft.zcm.cmdb.domain.extra.UserListDto;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.zcm.core.remote.RestClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

@Component("portalUserRequestHelper")
public class PortalUserRequestHelper {

    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(PortalUserRequestHelper.class);

    @Autowired
    private RestClient restClient;

    @Value("${portal.module.url}")
    private String portalModuleUrl;

    public List<UserDto> getAllPortalUsers() {
        List<UserDto> userlist = null;
        String getUserListUrl = portalModuleUrl + "/users";
        ParameterizedTypeReference<UserListDto> typeRef = new ParameterizedTypeReference<UserListDto>() {
        };
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        try {
            final ResponseEntity<UserListDto> responseEntity = restClient.exchange(getUserListUrl, HttpMethod.GET,
                    new HttpEntity<>(null, httpHeaders), typeRef, new HashMap());

            userlist = responseEntity.getBody().getList();
        }
        catch (Exception e) {
            LOGGER.error(e);
        }
        return userlist;
    }

    public List<UserDto> getPortalUserByIds(List<Integer> userIdList) {
        if (null == userIdList || userIdList.size() <= 0) {
            return null;
        }
        List<UserDto> userlist = null;
        String userIds = StringUtils.join(userIdList, ",");
        String getUserListUrl = portalModuleUrl + "/users/userIds/" + userIds;
        ParameterizedTypeReference<List<UserDto>> typeRef = new ParameterizedTypeReference<List<UserDto>>() {
        };
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        try {
            final ResponseEntity<List<UserDto>> responseEntity = restClient.exchange(getUserListUrl, HttpMethod.GET,
                    new HttpEntity<>(null, httpHeaders), typeRef, new HashMap());

            userlist = responseEntity.getBody();
        }
        catch (Exception e) {
            LOGGER.error(e);
        }
        return userlist;
    }
}
